package language.advanced.reflect;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CustomClassLoader extends ClassLoader {
    private String classPath; // 类路径

    public CustomClassLoader(String classPath) {
        this.classPath = classPath;
    }

    // 重写findClass方法，只加载以Custom为前缀的类
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        if (name.startsWith("Custom")) {
            byte[] data = loadClassData(name);
            return defineClass(name, data, 0, data.length);
        } else {
            // 如果不是以Custom为前缀的类，则委派给父类加载
            return super.findClass(name);
        }
    }

    // 从指定路径中读取class文件内容，返回byte数组
    private byte[] loadClassData(String className) {
        String fileName = className.replace(".", "/") + ".class";
        try (FileInputStream fis = new FileInputStream(new File(classPath, fileName))) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
